<script setup>
import { showToast } from 'vant'
import { ref, onMounted } from 'vue'
import { userGetListService, userLoginService } from '@/api/user'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores'

const router = useRouter()
const route = useRoute()

const onClickLeft = () => history.back()

const columns = ref([])

const onConfirm = ({ selectedOptions }) => {
  showPicker.value = false
  fieldValue.value = selectedOptions[0].text
  userId.value = selectedOptions[0].value
}

const fieldValue = ref('')
const userId = ref('')
const showPicker = ref(false)

// 进入页面， 调用方法获取所有用户
// 给下拉选项框绑定用户
onMounted(async () => {
  const res = await userGetListService()
  res.data.data.forEach((user) => {
    columns.value.push({ text: user.name, value: user.id })
  })
  userId.value = 4
  fieldValue.value = '测试账号'
})

const btnLoading = ref(false)

// 授权码
const code = ref('123456')
// 用户
const userStore = useUserStore()

// 按钮点击确认啦
const submitBth = async () => {
  btnLoading.value = true
  // 校验下拉菜单是否选择了
  if (
    !fieldValue.value === '' ||
    userId.value === '' ||
    code.value.trim() === ''
  ) {
    showToast({
      message: '未选择用户或输入授权码',
      position: 'bottom'
    })
    btnLoading.value = false
    return
  }

  // 授权码和用户都选择了，发送请求后端台选择用户
  const { data } = await userLoginService({
    id: userId.value,
    name: fieldValue.value,
    code: code.value
  })
  if (data.code === 1) {
    // 将名字跟id 存入仓库
    userStore.setUser({
      id: userId.value,
      name: fieldValue.value
    })
    // 授权成功，跳转到上一页
    router.go(-1)
  }
  btnLoading.value = false
}
</script>

<template>
  <div>
    <!-- 头部 -->
    <van-nav-bar
      title="选择用户"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 选择用户 -->
    <van-field
      v-model="fieldValue"
      is-link
      readonly
      label="用户"
      placeholder="选择用户"
      @click="showPicker = true"
    />
    <!-- 下拉框 -->
    <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker
        class="dorp"
        :columns="columns"
        @cancel="showPicker = false"
        @confirm="onConfirm"
      />
    </van-popup>

    <van-cell-group inset class="dorp">
      <van-field
        v-model="code"
        label="验证授权"
        left-icon="goods-collect-o"
        placeholder="输入授权码"
      />
    </van-cell-group>
    <van-button
      @click="submitBth"
      class="btn"
      type="primary"
      size="small"
      :loading="btnLoading"
      loading-text="确认中..."
      >确认</van-button
    >
  </div>
</template>

<style lang="less" scoped>
.dorp {
  margin-left: 0;
}

.btn {
  margin-top: 10px;
  width: 100px;
  align-self: center;
  margin-left: 120px;
}
</style>
